var gBlogObject = null;
var gTempBlogObject = new Object();

var SCRIBEFIRE_ACCWIZ = {
	currentScreen : null,
	
	loginTimeout : null,
	
	custom : false,
	
	autoDeck : null,
	customList : null,
	serviceList : null,
	
	load : function () {
		this.custom = false;
		this.autoDeck = document.getElementById("autodetect-deck");
		this.serviceList = document.getElementById("performancing-blogservice-list");
		this.customList = document.getElementById("performancing-blogservice-custom-list");
		
		var panels = document.getElementById("accountwizard").parentNode.childNodes;
		
		for (var i = 0; i < panels.length; i++) {
			panels[i].style.display = 'none';
		}
		
		document.getElementById("blog-url").value = "http://www.example.com/blog/";
		document.getElementById("accountwizard").style.display = '';
		this.autoDeck.selectedIndex = 0;

		this.goTo('start');
	},
	
	back : function () {
		switch (this.currentScreen) {
			case 'start':
			break;
			case 'login':
				if (!this.custom) {
					this.load();
				}
				else {
					this.goTo("custom-settings");
				}
			break;
			case 'login-error':
				this.goTo('login');
			break;
			case 'login-loading':
				this.goTo('login');
			break;
			case 'custom-settings':
				this.goTo('start');
			break;
		}
	},
	
	next : function () {
		switch (this.currentScreen) {
			case 'start':
				this.checkURL();
			break;
			case 'login':
				if (!this.custom) {
					var serviceList = this.serviceList;
					var appKey = serviceList.selectedItem.getAttribute("apikey");
					var apiUrl = serviceList.selectedItem.getAttribute("apiurl");
				}
				else {
					var serviceList = document.getElementById('performancing-blogservice-custom-list');
					var appKey = document.getElementById('custom-appkey').value;
					var apiUrl = document.getElementById('custom-apiurl').value;
				}
				
				var blogType = serviceList.selectedItem.value;
				var apiType = serviceList.selectedItem.getAttribute("api");
				var username = document.getElementById('username').value;
				var password = document.getElementById('password').value;
				
				if (username != "" && password != ""){
					document.getElementById("login-error-msg").hidden = true;
					
					var isAtom = false;
					var serviceObject = null;
					
					switch(apiType){
						case "s_mt":
							serviceObject = new perFormancingMovableTypeAPI();
						break;

						case "s_blogger":
							serviceObject = new perFormancingBloggerAPI();
						break;

						case "s_metaweblog":
							serviceObject = new performancingMetaweblogAPI();
						break;

						case "s_tumblr":
							serviceObject = new performancingTumblrAPI();
							isAtom = true;
						break;

						// Start Custom/Standard API's

						case "atom": //https://blogger.com/atom
							serviceObject = new perFormancingAtomAPI();
							isAtom = true;
						break;

						case "atom_blogger": //https://blogger.com/ Beta
							serviceObject = new perFormancingBloggerAtomAPI();
							isAtom = true;
						break;

						case "mt":
							serviceObject = new perFormancingMovableTypeAPI();
						break;

						case "blogger":
							serviceObject = new perFormancingBloggerAPI();
						break;

						case "metaweblog":
							serviceObject = new performancingMetaweblogAPI();
						break;

						default:
							alert(performancingUI.getLocaleString('awnoservicechosen'));
							return false;
						break;
					}
					
					apiUrl = apiUrl.replace("_USER_NAME_", username);

					// Blogger
					serviceObject.doSetup();
					serviceObject.init(blogType, appKey, apiUrl, null, null, username,  password, false  );

					// Setup temp object
					gTempBlogObject.blogtype = blogType;
					gTempBlogObject.blogapi = apiType;
					gTempBlogObject.apiurl = apiUrl;
					gTempBlogObject.appkey = appKey;

					var xmlRequest = serviceObject.getUsersBlogs();

					if (xmlRequest && !isAtom){
						performancing_xmlcall.sendCommand(apiUrl, xmlRequest, 'accountwizard', "", "", performancing_xmlcall.processData);
						
						SCRIBEFIRE_ACCWIZ.loginTimeout = window.setTimeout(
							function () {
								alert(performancingUI.getLocaleString("accountWizardLoginTimeout"));
								SCRIBEFIRE_ACCWIZ.goTo('login');
							},
							15000);
					}
					
					this.goTo('login-loading');

					return true;
				}
				else {
					document.getElementById("login-error-msg").hidden = false;
				}
			break;
			case 'success':
				performancingUI.reLoadBlogs();
				SF_MOB.toolbarButtonPress(1);
			break;
			case 'custom-settings':
				this.goTo('login');
			break;
		}
	},
	
	cancel : function () {
		SF_MOB.toolbarButtonPress(0);
	},
	
	setNavigation : function () {
		var back = document.getElementById("accountwizard-back");
		var cancel = document.getElementById("accountwizard-cancel");
		var next = document.getElementById("accountwizard-next");
		
		back.style.display = '';
		cancel.style.display = '';
		next.style.display = '';
		
		switch (this.currentScreen) {
			case 'start':
				back.style.display = 'none';
			break;
			
			case 'custom-settings':
			
			break;
			
			case 'login':
			
			break;
			
			case 'login-loading':
				next.style.display = 'none';
			break;
			
			case 'login-error':
				next.style.display = 'none';
			break;
			
			case 'success':
				back.style.display = 'none';
				cancel.style.display = 'none';
			break;
		}
	},
	
	goTo : function (scr) {
		var screens = document.getElementById("accountwizard").childNodes;
		
		for (var i = 0; i < screens.length; i++) {
			screens[i].style.display = 'none';
		}
		
		document.getElementById("accountwizard-screen-"+scr).style.display = '';
		document.getElementById("accountwizard-navigation").style.display = '';
		
		this.currentScreen = scr;
		this.setNavigation();
		
		if (scr === 'start') {
			this.custom = false;
			this.autoDeck.selectedIndex = 0;
		}
	},
	
	checkURL : function () {
		// Check if it's one of the standard blogging services.
		var theDomain = document.getElementById("blog-url").value;
		var service = null;
		
		if (theDomain.search(/\.wordpress\.com/) != -1) {
			service = "wordpress";
		}
		else if (theDomain.search(/\.typepad\.com/) != -1 || theDomain.search(/\.blogs\.com/) != -1){
			service = "typepad";
		}
		else if (theDomain.search(/livejournal\.com/) != -1){
			service = "livejournal";
		}
		else if(theDomain.search(/spaces\.msn\.com/) != -1 || theDomain.search(/spaces\.live\.com/) != -1){
			service = "spaces";
		}
		else if(theDomain.search(/performancing\.com/) != -1){
			service = "performancing";
		}
		else if(theDomain.search(/jeeran\.com/) != -1){
			service = "jeeran";
		}
		else if (theDomain.search(/tumblr\.com/) != -1) {
			service = "tumblr";
		}
		else if (theDomain.search(/splinder\.com/) != -1) {
			service = "splinder";
		}
		else if (theDomain.search(/insanejournal\.com/) != -1) {
			service = "insanejournal";
		}
		else if (theDomain.search(/xanga\.com/) != -1) {
			service = "xanga";
		}
		
		if (service !== null) {
			var items = this.serviceList.menupopup.childNodes;
			
			for (var i = 0; i < items.length; i++) {
				if (items[i].getAttribute("service") == service) {
					this.serviceList.selectedIndex = i;
					break;
				}
			}
			
			return this.goTo("login");
		}
		
		this.custom = true;
		
		// If it's not, try to auto-detect it.
		this.autoDeck.selectedIndex = 1;
		
		// Make sure it's a valid URL:
		if (theDomain.search("http://") == "-1" && theDomain.search("https://") == "-1"){
			theDomain = "http://" + theDomain;
		}
		
		var theCall = new PffXmlHttpReq(theDomain, "GET", null, false, null, null);
		
		theCall.onResult = function( aText, aXML ){
			SCRIBEFIRE_ACCWIZ.processAutoDetectPage(aText, 'plain');
		};
		
		theCall.onError = function (aStatusMsg, Msg) {
			// alert("Error: " + aStatusMsg + " " + Msg);
			SCRIBEFIRE_ACCWIZ.autoDeck.selectedIndex = 3;
		};

		theCall.prepCall();
		theCall.makeCall();
	},
	
	configureManually : function () {
		this.custom = true;
		this.goTo('custom-settings');
	},
	
	tryAgain : function (){
		this.autoDeck.selectedIndex = 0;
	},
	
	clearLoginTimeOut : function (){
		clearTimeout(SCRIBEFIRE_ACCWIZ.loginTimeout);
	},
	
	processReturnData : function (theObject, isAtom, theXML){
		document.getElementById("faultString").collapsed = true;

		SCRIBEFIRE_ACCWIZ.clearLoginTimeOut();

		if ("faultString" in theObject) {
			var node = document.getElementById("faultStringContent");

			while (node.firstChild) node.removeChild(node.firstChild);
			
			document.getElementById("faultStringContent").appendChild(document.createTextNode(theObject.faultString));

			document.getElementById("faultString").collapsed = false;
			
			this.goTo('login-error');
		}
		else if(theObject.length != null){
			// Add the blog here.
			
			var db = SCRIBEFIRE_DB.getDB();
			
			gBlogObject = theObject;
			
			var theBlogType = gTempBlogObject.blogtype;
			var theBlogAPI = gTempBlogObject.blogapi;
			var theAppKey = gTempBlogObject.appkey;
			var theAPIURL = gTempBlogObject.apiurl;
			var theAppKey = gTempBlogObject.appkey;
			
			var theUserName = document.getElementById('username').value;
			var thePassWord = document.getElementById('password').value;
			var useBoolean = document.getElementById('useBooleanForPublish').checked;
			
			for (var j = 0; j < gBlogObject.length; j++) {
				var theBlogName = gBlogObject[j].blogName;
				var theGUID = this.newGuid();
				var theURL = gBlogObject[j].url;
				var theBlogID = gBlogObject[j].blogid;
			
				// First 3 are for legacy support (v1.0)
				if (theBlogType == "blogger_com" || theBlogType == "atom_cust" || theBlogType == "livejournal_atom_com" || theBlogType == "s_atom" || theBlogType == "atom" || theBlogType == "__atom_blogger"){
					theAPIURL = gBlogObject[j].url;
				}

				var insert = db.createStatement("INSERT INTO "+SCRIBEFIRE_DB.blogsTable+" (name, type, key, username, api, guid, url, blogId, useBoolean) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)");
				insert.bindUTF8StringParameter(0, theBlogName);
				insert.bindUTF8StringParameter(1, theBlogType);
				insert.bindUTF8StringParameter(2, theAppKey);
				insert.bindUTF8StringParameter(3, theUserName);
				insert.bindUTF8StringParameter(4, theAPIURL);
				insert.bindUTF8StringParameter(5, theGUID);
				insert.bindUTF8StringParameter(6, theURL);
				insert.bindUTF8StringParameter(7, theBlogID);
				insert.bindUTF8StringParameter(8, useBoolean);
				insert.execute()
				
				gPerformancingUtil.usermanagment.storeLoginDetails(theUserName, thePassWord, theURL);			
			}
			
			SCRIBEFIRE_DB.closeDB(db);
			
			this.goTo('success');
		}
	},
	
	processAutoDetectPage : function (theXMLData, dataFormat) {
		var theResult = null;
		
		try {
			if (dataFormat == 'plain'){
				this.findServiceFromLinkTag(theXMLData);
				return;
			}
			else if (dataFormat == 'xml'){
				theResult = this.findServiceFromApiTag( theXMLData );
			}
			else if (dataFormat == 'parsed' ) {
				theResult = theXMLData;
			}
			else {
				theResult = [false, null, null];
			}

			if (theResult[0]){
				var theAPI = theResult[1];
				var theURL = theResult[2];

				switch(theAPI){
					case "wordpress":
						this.customList.selectedIndex = 0;
					break;
					
					case "blogger":
					break;
					
					case "blogger_beta":
						this.customList.selectedIndex = 6;
					break;

					case "metaweblog":
						this.customList.selectedIndex = 5;
					break;

					case "movabletype":
						this.customList.selectedIndex = 1;
					break;
				}

				this.serviceList.selectedIndex = 10;
				this.onCustomListClick();
				
				document.getElementById('custom-apiurl').value = theURL;
				
				this.goTo('custom-settings');
			}
			else {
				this.autoDeck.selectedIndex = 3;
			}
		} catch (e) {
			alert(e);
			this.autoDeck.selectedIndex = 3;
		}
	},
	
	findServiceFromLinkTag : function (theXMLData){
		gPerformancingUtil.convertTextToHTML(theXMLData, function (a,b,c) { SCRIBEFIRE_ACCWIZ.findServiceFromLinkTagDOM(a,b,c); });
	},

	findServiceFromLinkTagDOM : function (text, notUsed, doc) {
		var linkTags = doc.getElementsByTagName("link");

		for (var i = 0; i < linkTags.length; i++) {
			var rel = linkTags[i].getAttribute("rel");
			var type = linkTags[i].getAttribute("type");
			var title = linkTags[i].getAttribute("title");
			var href = linkTags[i].getAttribute("href");

			if (rel && type && href && rel == 'service.post' && type == 'application/atom+xml' && href.indexOf("posts/") != -1) {
				return this.processAutoDetectPage( [true, "blogger_beta", href], 'parsed' );
			}
			else if (rel && href && rel == 'pingback') {
				return this.processAutoDetectPage( [true, 'wordpress', href], 'parsed' );
			}
			else if (title && href && title == 'RSD') {
				return this.checkForRSD(href);
			}
		}
		
		return this.processAutoDetectPage( [ false, null, null ], 'parsed');
	},

	checkForRSD : function (aURL){
		var theCall = new PffXmlHttpReq(aURL, "GET", null, false, null, null);

		theCall.onResult = function( aText, aXML ){
			SCRIBEFIRE_ACCWIZ.processAutoDetectPage(aXML, 'xml');
		};

		theCall.onError = function (aStatusMsg, Msg) {
			// This will result in the "cannot auto-detect" error being shown
			alert(aStatusMsg + " " + Msg);
			SCRIBEFIRE_ACCWIZ.processAutoDetectPage();
		};

		theCall.prepCall();
		theCall.request.setRequestHeader("Content-Type", "text/xml");
		theCall.makeCall();
		theCall.request.overrideMimeType('text/xml');
	},

	findServiceFromApiTag : function (theXMLData) {
		try {
			var engines = theXMLData.getElementsByTagName("engineName");
			
			if (engines.length > 0) {
				var engine = engines[0];
				
				if (engine.textContent == 'TypePad') {
					this.serviceList.selectedIndex = 1;
					this.autoDeck.selectedIndex = 1;
					this.goTo("login");
					
					return;
				}
			}
			
			var apis = theXMLData.getElementsByTagName("api");

			for (var i = 0; i < apis.length; i++) {
				var name = apis[i].getAttribute("name").toLowerCase();
				var apiLink = apis[i].getAttribute("apiLink");

				if (name=="blogger") {
					return [true, "blogger", apiLink];
				}
				else if (name=="metaweblog") {
					return [true, "metaweblog", apiLink];
				}
				else if (name=="movabletype" || name == "movable type") {
					return [true, "movabletype", apiLink];
				}
				else if (name=="wordpress") {
					return [true, "wordpress", apiLink];
				}
			}
		} catch(e) {
			alert(e);
		}

		return [false, "error"];
	},
	
	onCustomListClick : function (){
		var aCustomServiceAPI = this.customList.selectedItem.getAttribute("apiurl");
		var customAPIBox = document.getElementById('custom-apiurl');
		customAPIBox.value = aCustomServiceAPI;

		if (this.customList.selectedItem.value == 'roller_cust'){
			var localeString = performancingUI.getLocaleString('awrollersupport', []);
			alert(localeString);
		}
		
		if (this.customList.selectedItem.getAttribute("useBoolean") == 'true'){
			document.getElementById('useBooleanForPublish').checked = true;
		}
		else {
			document.getElementById('useBooleanForPublish').checked = false;
		}
	},
	
	newGuid : function () {
		var g = ""; 
		for(var i = 0; i < 32; i++){
			g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : ""); 
		}
		return g;
	}
};